package top.songxs.gmall.common.service;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import top.songxs.gmall.common.properties.MinioProperties;

import java.util.UUID;

public class FileUploadService {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;

    public String upload(MultipartFile file) {

        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        .build());
            } else {
                System.out.println("bucket桶已经存在");
            }
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            String fullFilename = uuid + "." + extension;

            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .object(fullFilename)
                    .bucket(minioProperties.getBucketName())
                    .build();
            minioClient.putObject(putObjectArgs);

          /*  URL url = new URL(minioProperties.getEndpoint());
            String host = url.getHost();
            String protocol = url.getProtocol();
            String uri = protocol+"://"+host;*/
            //把endpoint中的端口号去掉
//            String filePath =uri +"/"+minioProperties.getBucketName()+"/"+fullFilename;
            String filePath =minioProperties.getEndpoint() +"/"+minioProperties.getBucketName()+"/"+fullFilename;
            System.out.println(filePath);
            return filePath;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }




}
